package com.zx.framework.core.util.zxing;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class ZxingUtil {
	
	public static BitMatrix generate(String content,int width, int height) throws WriterException{
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,  
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵  
        return bitMatrix;
	}
	/**
	 * 将二维码写入流
	 * @param content 内容
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param format 格式
	 * @param stream 输出流
	 * @throws WriterException
	 * @throws IOException
	 */
	public static void WriteToStream(String content,int width, int height,String format,OutputStream stream) throws WriterException, IOException{
		BitMatrix bitMatrix = generate(content, width, height);
		MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
	}
	/**
	 * 将二维码写入到文件
	 * @param content 内容
	 * @param filePath 文件目录
	 * @param fileName 文件名称
	 * @param width 宽度
	 * @param height 高度
	 * @param format 格式
	 * @throws WriterException
	 * @throws IOException
	 */
	public static void WriteToPath(String content,String filePath,String fileName,int width, int height,String format) throws WriterException, IOException{
		BitMatrix bitMatrix = generate(content, width, height);
		Path path = FileSystems.getDefault().getPath(filePath, fileName);  
		MatrixToImageWriter.writeToPath(bitMatrix, format, path);
	}
	
}
